import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {environment} from '../../environments/environment';
import {StorageService} from '../services/storage.service';
declare var $: any;
@Injectable()
export class ReportService {
  constructor(private http: HttpClient, private  storageService: StorageService) { }
  //添加
  onSubmitReport(report) {
    let token = this.storageService.getToken('token');
    return this.http.post(`${environment.url.management}/fault`, {
      'access_token': token,
      'type': 'fault_add',
      'data': {
        'cid': report.cid,
        'people': report.people,
        'fault_type': report.fault_type,
        'status': report.status,
        'time': report.time,
        'location': report.location,
        'content': report.content,
        'title': report.title,
        'handle_people': report.handle_people,
        'handle_datetime': report.handle_datetime,
        'img_url': report.img_url,
        'devices': report.submitdevices,
      }
    }).map((res: Response) => {
      if (res['errcode'] !== '00000'){
        throw new Error(res['errmsg']);
      }
      return res['datas'];
    });
  }
  //修改

  updateReport(report) {
    let token = this.storageService.getToken('token');
    return this.http.post(`${environment.url.management}/fault`, {
      access_token: token,
      type: 'fault_mod',
      'data': {
        'people': report.people,
        'cid': report.cid,
        'fault_type': report.fault_type,
        'status': report.status,
        'time': report.time,
        'location': report.location,
        'content': report.content,
        'title': report.title,
        'handle_people': report.handle_people,
        'handle_datetime': report.handle_datetime,
        'img_url': report.img_url,
        'devices': report.subdevices,
      }
    }).map((res: Response) => {
      if (res['errcode'] !== '00000'){
        throw new Error(res['errmsg']);
      }
      return res['data'];
    });
  }

  //查询历史报障
  getHistoryReport(report){
    let token = this.storageService.getToken('token');
    return this.http.post(`${environment.url.management}/fault`, {
      'access_token': token,
      'type': 'fault_get',
      'data': {
          'cid': report.cid,
          'people': report.people,
          'fault_type': report.fault_type,
          'status': report.status,
          'time_start': report.time_start,
          'time_end': report.time_end,
        }
    }).map((res: Response) => {
      if (res['errcode'] !== '00000'){
        throw new Error(res['errmsg']);
      }
      return res['datas'];
    });
  }
  //删除保障单接口
  deleteReport(cids) {
    let token = this.storageService.getToken('token')
    return this.http.post(`${environment.url.management}/fault`, {
      "access_token":token,
      "type": "fault_del",
      "cids":[cids]
    }).map((res:Response) => {
      if (res['errcode'] !== '00000') {
        throw new Error(res['errmsg']);
      }
      return res['data'];
    })
  }
  //  报障总览查询
  getReportView(){
    let token = this.storageService.getToken('token');
    return this.http.post(`${environment.url.management}/fault`, {
      'access_token': token,
      'type': 'fault_statistics',
    }).map((res: Response) => {
      if (res['errcode'] !== '00000'){
        throw new Error(res['errmsg']);
      }
      return res['datas'];

    });
  }

  //搜索建议
  searchChange(queryModel){
    return this.http.post(`${environment.url.management}/fault`, {
      'access_token': '',
      'type': 'asset_diffield_get',
        'data': {
            'field': queryModel.field,
            'value': queryModel.value
        }


    }).map((res: Response) => {
      if (res['errcode'] !== '00000'){
        throw new Error(res['errmsg']);
      }
      return res['datas'];
    });
  }

    handleReport(report){
        let token = this.storageService.getToken('token');
        return this.http.post(`${environment.url.management}/fault`, {
            'access_token': token,
            'type': 'fault_handle',
            'data': {
                'cid': report.id,
                'handle_content': report.handle_content
            }
        }).map((res: Response) => {
            if (res['errcode'] !== '00000'){
                throw new Error(res['errmsg']);
            }
            return res['datas'];
        });
    }
  //查询资产
  getAssets() {
    let token = this.storageService.getToken('token');
    return this.http.post(`${environment.url.management}/asset`, {
      'access_token': token,
      'type': 'asset_get'
    }).map((res: Response) => {
      if (res['errcode'] !== '00000'){
        throw new Error(res['errmsg']);
      }
      return res['datas'];
      // let body = res.json();
      // if (body.errcode !== '00000') {
      //   throw new Error(body.errmsg);
      // }
      // return body.datas
    });
  }
  //查找功能
  queryByKeyWords(asset){
    let token = this.storageService.getToken('token');
    return this.http.post(`${environment.url.management}/asset`, {
      'access_token': token,
      'type': 'asset_get',
      'datas': {
        'ano': asset.ano,
        'father': asset.father,
        'card_position': asset.card_position,
        'asset_no': asset.asset_no,
        'name': asset.name,
        'brand': asset.brand,
        'modle': asset.modle,
        'function': asset.function,
        'system': asset.system,
        'status': asset.status,
        'on_line_date_start': asset.on_line_date_start,
        'on_line_date_end': asset.on_line_date_end,
        'room': asset.room,
        'cabinet': asset.cabinet,
        'location': asset.location,
        'belong_dapart': asset.belong_dapart,
        'belong_dapart_manager': asset.belong_dapart_manager,
        'manage_dapart': asset.manage_dapart,
        'manager': asset.manager,
        'ip': asset.ip,
        'maintain_vender': asset.maintain_vender
      }
    }).map((res: Response) => {
      if (res['errcode'] !== '00000'){
        throw new Error(res['errmsg']);
      }
      return res['datas'];
      // let body = res.json();
      // if(body.errcode!=='00000'){
      //   throw new Error(body.errmsg)
      // }
      // return body.datas
    });
  }
  //所有状态获取接口
  getStatusReport(){
    let token = this.storageService.getToken('token');
    return this.http.post(`${environment.url.management}/fault`, {
      'access_token': token,
      'type': 'fault_get_allstatus',
    }).map((res: Response) => {
      if (res['errcode'] !== '00000'){
        throw new Error(res['errmsg']);
      }
      return res['datas'];
    });
  }
  //保障发起保存接口
  queryReportSave(report){
    let token =this.storageService.getToken('token');
    return this.http.post(`${environment.url.management}/fault`,{
      "access_token":token,
      "type":"fault_save",
      "data": {
        'people': report.people,
        'fault_type': report.fault_type,
        'status': report.status,
        'time': report.time,
        'location': report.location,
        'content': report.content,
        'title': report.title,
        'handle_people': report.handle_people,
        'handle_datetime': report.handle_datetime,
        'img_url': report.img_url,
        "devices":report.submitdevices
      }
    }).map((res:Response)=>{

      if(res['errcode'] !== '00000'){
        let reg = /No datas/;
        if(res['errmsg'].search(reg)!==-1){
          return [];
        }
        throw  new Error(res['errmsg'])
      }
      return res['data'];
    })
  }
  formatPieData(arr){
    let newarr = [];
    for (let i = 0; i < arr.length; i++){
      let obj = {};
      let def = arr[i];
      obj['name'] = def ['name'];
      obj['value'] = def['count'];
      newarr.push(obj);
    }
    return newarr;
  }
  formatDropdownData(arr){
    let newarr = [];
    for (let i = 0; i < arr.length; i++){
      let obj = {};
      let temp = arr[i];
      obj['label'] = temp['name'];
      obj['value'] = temp['code'];
      newarr.push(obj);
    }
    return newarr;
  }
  getFormatTime(date?) {
    if (!date){
      date = new Date();
    }else{
      date = new Date(date);
    }
    let day = date.getDate();
    let month = date.getMonth() + 1;
    let year = date.getFullYear();
    let hour = date.getHours();
    let minutes = date.getMinutes();
    let second = date.getSeconds();
    day = day <= 9 ? '0' + day : day;
    month = month <= 9 ? '0' + month : month;
    hour = hour <= 9 ? '0' + hour : hour;
    minutes = minutes <= 9 ? '0' + minutes : minutes;
    second = second <= 9 ? '0' + second : second;
    return  year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + second;

  }
  deepClone(obj){
    var o,i,j,k;
    if(typeof(obj)!="object" || obj===null)return obj;
    if(obj instanceof(Array))
    {
      o=[];
      i=0;j=obj.length;
      for(;i<j;i++)
      {
        if(typeof(obj[i])=="object" && obj[i]!=null)
        {
          o[i]=this.deepClone(obj[i]);
        }
        else
        {
          o[i]=obj[i];
        }
      }
    }
    else
    {
      o={};
      for(i in obj)
      {
        if(typeof(obj[i])=="object" && obj[i]!=null)
        {
          o[i]=this.deepClone(obj[i]);
        }
        else
        {
          o[i]=obj[i];
        }
      }
    }
    return o;
  }
}
